
import { FontType as OriginalFontType } from "element-tiptap";
import { getMarkAttrs } from 'tiptap-utils'
import CustomMenuButton from './MenuButton.vue'

const DEFAULT_FONT_TYPE = ''

export default class FontType extends OriginalFontType {
    constructor(option = {}) {
        super(option)
        this.fontTypes = option.fontTypes || {
            'Arial': 'Arial',
            'Arial Black': 'Arial Black',
            'Georgia': 'Georgia',
            'Impact': 'Impact',
            'Tahoma': 'Tahoma',
            'Times New Roman': 'Times New Roman',
            'Verdana': 'Verdana',
            'Courier New': 'Courier New',
            'Lucida Console': 'Lucida Console',
            'Monaco': 'Monaco',
            'monospace': 'monospace',
        }
    }
    menuBtnView(editorContext) {
        return {
            component: CustomMenuButton,
            componentProps: {
                fontTypes: this.fontTypes,
                isActive: editorContext.isActive.font_type()
            },
            componentEvents: {
                command(fontType) {
                    let activeFontType = findActiveFontType(editorContext.editor.state)
                    if (fontType === activeFontType) editorContext.commands.font_type(DEFAULT_FONT_TYPE)
                    else editorContext.commands.font_type(fontType)
                }
            }
        };
    }
}

function findActiveFontType(state) {
    const { schema, selection, tr } = state;
    const markType = schema.marks.font_type;

    if (!markType) return DEFAULT_FONT_TYPE;

    const { empty } = selection;

    if (empty) {
        return
        const storedMarks = tr.storedMarks ||
            state.storedMarks ||
            (
                selection instanceof TextSelection &&
                selection.$cursor &&
                selection.$cursor.marks &&
                selection.$cursor.marks()
            ) ||
            [];

        const sm = storedMarks.find((m) => m.type === markType);
        return (sm && sm.attrs.name) || DEFAULT_FONT_TYPE;
    }

    const attrs = getMarkAttrs(state, markType);
    const fontName = attrs.name;

    if (!fontName) return DEFAULT_FONT_TYPE;

    return fontName;
}